package cn.itcast.homework.service;

import cn.itcast.homework.dto.PageResult;
import cn.itcast.homework.dto.SearchRequest;
import cn.itcast.homework.entity.Item;
import cn.itcast.homework.es.mapper.HighlightResultMapper;
import cn.itcast.homework.mapper.ItemMapper;
import cn.itcast.homework.po.ItemPO;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author 虎哥
 */
@Service
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;

    public ItemPO queryById(Long id) {
        return itemMapper.selectByPrimaryKey(id);
    }

    public Long save(ItemPO itemPO) {
        int id = new Random().nextInt(100);
        System.out.println("id = " + id);
        if(id < 50){

            throw new RuntimeException("参数有误");
        }

        return Long.valueOf(id);
    }

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public PageResult search(SearchRequest request) {
        PageResult pageResult = new PageResult();
        // 1.原生查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 2.利用构建器构建查询条件
        // 2.1.关键字搜索
        String key = request.getKey();
        if (StringUtils.isBlank(key)) {
            // 关键字为空，不做查询，返回null
            return pageResult;
        }
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", key));
        // 2.2.分页
        int page = request.getPage() == null ? 1 : request.getPage();
        int size = request.getSize()== null ? 10 : request.getSize();
        queryBuilder.withPageable(PageRequest.of(page - 1, size));
        //TODO 2.3.排序
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
        queryBuilder.withSort(SortBuilders.fieldSort("sold").order(SortOrder.DESC));
        // 2.4.高亮
        queryBuilder.withHighlightFields(new HighlightBuilder.Field("title"));

        NativeSearchQuery query = queryBuilder.build();


        // 3.利用template发起请求，完成查询，得到结果
        AggregatedPage<Item> result = elasticsearchTemplate.queryForPage(query, Item.class, new HighlightResultMapper());


        // 4.解析结果
        long total = result.getTotalElements();
        int totalPage = result.getTotalPages();
        List<Item> items = result.getContent();

        // 5.封装返回结果
        pageResult.setTotal(total);
        pageResult.setTotalPage(totalPage);
        pageResult.setItems(items);
        return pageResult;
    }
}
